package com.aifast.dict.core;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.aifast.dict.annotations.DictBind;
import com.aifast.dict.common.Const;
import com.aifast.dict.common.FastDictType;
import com.aifast.dict.properties.FastDictProperties;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @Author AiFast
 * @since 2022/12/28 15:16
 */
public class FastDictTranslator {

//    private static FastDictTranslator translator;
    @Autowired
    private IFastDictService service;
    @Autowired
    private FastDictProperties properties;

    /*@PostConstruct
    public void init() {
        translator = this;
        translator.service = this.service;
    }*/

    public String genTargetFieldValue(DictBind dictBind, Object value) {
        String result = null;
        String type = dictBind.type();

        FastDictType mode = dictBind.mode();
        switch (mode) {
            case DICT:
                if (StrUtil.isBlank(type)) {
                    result = Const.EMPTY;
                    break;
                }
                if(StrUtil.isBlank(dictBind.joinSymbol())){
                    result = service.getDictDataValue(type, value);
                }else {
                    String[] strings = Convert.toStr(value).split(dictBind.joinSymbol());
                    result = getDictDataValue(dictBind.type(), strings,dictBind.joinSymbol());
                }
                break;
            case JOIN:
                if (StrUtil.isBlank(dictBind.joinSymbol())) {
                    result = getTableDataValue(dictBind.tableName(), dictBind.columns(),dictBind.idColumns(), value);
                } else {
                    String[] strings = Convert.toStr(value).split(dictBind.joinSymbol());
                    result = getTableDataValue(dictBind, strings);
                }
                break;
        }
        return result;
    }


    public String genTargetFieldName(String currentName, String target) {
        return StrUtil.isBlank(target) ? StrUtil.join(Const.EMPTY, currentName, Const.suffix) : target;
    }

    public String getDictDataValue(String type,String[] strings,String joinSymbol){
        return Arrays.stream(strings).map(x -> {
            return service.getDictDataValue(type,x);
        }).collect(Collectors.joining(joinSymbol));
    }

    private String getTableDataValue(DictBind dictBind, String[] strings) {
        return Arrays.stream(strings).map(x -> {
            return getTableDataValue(dictBind.tableName(), dictBind.columns(),dictBind.idColumns(), x);
        }).collect(Collectors.joining(dictBind.joinSymbol()));
    }

    private String getTableDataValue(String tableName, String columns,String idColumns, Object dataId) {
        return service.getTableDataValue(tableName, columns,idColumns, dataId);
    }


}
